'use strict';

const Service = require('egg').Service;

class UserRoleService extends Service {


  // 获取列表
  async findAll(pageNum, pageSize) {
    const { app } = this;
    try {
      const offset = (pageNum - 1) * pageSize;
      const { count, rows } = await app.model.Permission.findAndCountAll({
        offset,
        limit: pageSize * 1,
      });
      return {
        pageNum,
        pageSize,
        total: count,
        list: rows,
      };
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // 获取某个 资源
  async findOne(id) {
    return await this.app.model.Permission.findOne({ where: { id } });
  }

  // 新增
  async create(payload) {
    const { app } = this;
    const { url, action } = payload;
    const one = await app.model.Permission.findOne({ where: { url, action } });
    if (one) {
      const err = new Error('已存在');
      err.parent = {};
      err.parent.errno = 1062;
      throw err;
    }
    return await app.model.Permission.create(payload);
  }
  // 修改
  async updated(id, payload) {
    const { app } = this;
    const { url, action } = payload;
    const Op = app.Sequelize.Op;
    const one = await app.model.Permission.findOne({
      where: { id: { [Op.not]: id }, url, action },
    });
    if (one) {
      const err = new Error('已存在');
      err.parent = {};
      err.parent.errno = 1062;
      throw err;
    }
    return await app.model.Permission.update(payload, { where: { id } });
  }


  // 删除
  async del(payload) {
    const { app } = this;
    const delData = await app.model.Permission.findAll({
      where: { id: payload.ids },
    });
    return await app.model.Permission.destroy({ where: { id: payload.ids }, delData, force: true });
  }


}

module.exports = UserRoleService;
